//
//  PaywallView.swift
//  IncomeAndExpense
//
//  Created by HOA on 2021/8/21.
//

import SwiftUI
import Purchases

public struct PaywallView: View {
    
    /// - This binding is passed from ContentView: `paywallPresented`
    @Environment(\.presentationMode) var isPresent

    /// - State for displaying an overlay view
    @State var isPurchasing: Bool = false
    
    @State var displayPurchasList = false
    
    /// - The current offering saved from PurchasesDelegateHandler
    var offering: Purchases.Offering? = UserViewModel.shared.offerings?.current
    
    #warning("Modify this value to reflect your app's Privacy Policy and Terms & Conditions agreements. Required to make it through App Review.")
    var footerText = "Don't forget to add your subscription terms and conditions. Read more about this here: https://www.revenuecat.com/blog/schedule-2-section-3-8-b"
    
    @State var currentPurchasesPackage: Purchases.Package!
    
    @State var isPopPrivacy = false

    public init() {
        
    }
    
    public var body: some View {
        NavigationView {
            ZStack {
                /// - The paywall view list displaying each package
                List {
                    
                    VStack {
                        Image(uiImage: UIImage.init(contentsOfFile: Bundle.module.path(forResource: ["girl1", "girl2"].randomElement() ?? "girl1", ofType: "png")!) ?? UIImage())
                            .resizable()
                            .aspectRatio(1.5, contentMode: .fill)
                    }
                    .listRowInsets(.init(.init(top: 0, leading: 0, bottom: 0, trailing: 0)))
                    
                    Section(header: header, footer: footer) {
                        VStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 8, content: {
                            
                            payTitle
                            
                            Text("pay subtitle", bundle: .module)
                                .font(.title3)
                                .padding(.bottom, 20)
                            
                            Text("pay tip", bundle: .module)
                                .font(.callout)
                                .foregroundColor(Color.gray)
                                .padding(.bottom, 8)
                        })
                        .padding(.top, 8)
                    }
                    
                    if displayPurchasList {
                        Section(footer: Spacer().frame(height: 80)) {
                            ForEach(offering?.availablePackages ?? []) { package in
                                PackageCellView(package: package, currentPackage: $currentPurchasesPackage)
                            }
                        }
                    }
                    
                }
                .listStyle(InsetGroupedListStyle())
                .navigationBarTitleDisplayMode(.inline)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.bottom)
                .popover(isPresented: $isPopPrivacy, content: {
                    if let url = URL(string: "https://gitee.com/zero-time/Md/blob/master/README.md") {
                        TermsnprivacyView(url: url, isPoped: $isPopPrivacy)
                    }
                })
                .onAppear(perform: {
                    currentPurchasesPackage = offering?.availablePackages.first
                })
                .navigationBarItems(leading: Button(action: {
                    isPresent.wrappedValue.dismiss()
                }, label: {
                    Text("not now", bundle: .module)
                        .foregroundColor(.gray)
                }))
                
                VStack {
                    
                    Spacer()
                    
                    VStack {
                        
                        Button(action: {
                            
                            guard let package = currentPurchasesPackage ?? offering?.availablePackages.first else {
                                return
                            }
                            
                            isPurchasing = true
                            
                            /// - Purchase a package
                            Purchases.shared.purchasePackage(package) { (transaction, info, error, userCancelled) in
                                
                                /// - Set 'isPurchasing' state to `false`
                                isPurchasing = false
                                
                                /// - If the user didn't cancel and there wasn't an error with the purchase, close the paywall
                                if !userCancelled, error == nil {
                                    isPresent.wrappedValue.dismiss()
                                }
                            }
                            
                        }, label: {
                            HStack {
                                Spacer()
                                Text("continue", bundle: .module)
                                    .font(.headline)
                                    .frame(height: 55)
                                    .foregroundColor(.white)
                                Spacer()
                            }
                            .background(Color.blue)
                            .cornerRadius(14)
                        })
                        .padding(.bottom, 20)
                        .padding()
                    }
                    .edgesIgnoringSafeArea(.bottom)
                    .background(Color.black)
                }
                .edgesIgnoringSafeArea(.all)
                
                /// - Display an overlay during a purchase
                Rectangle()
                    .foregroundColor(Color.black)
                    .opacity(isPurchasing ? 0.5: 0.0)
                    .edgesIgnoringSafeArea(.all)
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
        .colorScheme(.dark)
    }
    
    /// 显示当前需要支付费用
    var payTitle: some View {
        Text(priceTitle)
            .font(.title3)
            .bold()
    }
    
    var priceTitle: String {
        
        if let package = currentPurchasesPackage ?? (offering?.availablePackages ?? []).first {
            return "\(package.product.localizedTitle), \(package.localizedPriceString)"
        } else {
            return ""
        }
        
    }
    
    /// header
    var header: some View {
        Text("pay title", bundle: .module)
            .font(.title)
            .bold()
            .foregroundColor(.white)
    }
    
    /// footer
    var footer: some View {
        HStack {
            
            Spacer()
            
            HStack(alignment: .center, spacing: 10) {
                Button(action: { isPopPrivacy.toggle() }, label: {
                    Text("terms and privacy", bundle: .module)
                })
                
                Spacer()
                    .frame(width: 1, height: 10)
                    .background(Color.gray)
                    .padding()
                
                Button(action: {
                    Purchases.shared.restoreTransactions(nil)
                }, label: {
                    Text("restore", bundle: .module)
                })
                
                Spacer()
                    .frame(width: 1, height: 10)
                    .background(Color.gray)
                    .padding()
                
                Button(action: {
                    displayPurchasList.toggle()
                }, label: {
                    Text("choose a plan", bundle: .module)
                })
            }
            
            Spacer()
        }
        .padding(.bottom, displayPurchasList ? 0 : 80)
    }
}

/* The cell view for each package */
struct PackageCellView: View {
    let package: Purchases.Package
    
    @Binding var currentPackage: Purchases.Package!
    
    var body: some View {
        HStack {
            VStack {
                HStack {
                    Text(package.product.localizedTitle)
                        .font(.title3)
                        .bold()
                    Spacer()
                }
            }
            .padding([.top, .bottom], 8.0)
            
            Spacer()
            
            Text(package.localizedPriceString)
                .font(.title3)
                .bold()
            
            Image(systemName: currentPackage == package ? "checkmark.seal.fill" : "seal")
                .font(.headline)
        }
        .onTapGesture {
            currentPackage = package
        }
    }
}
